<template>
  <!-- 供应商详细 -->
  <div class="supplier-detail">
    <!-- 上方容器：供应商基础资料 -->
    <div class="basic-info-container">
      <div class="section-header">
        <div class="section-title">供应商基础资料</div>
        <div class="section-actions">
          <el-button size="small" @click="JumptoEdit">编辑</el-button>
          <el-button size="small" @click="deleteSupplier">删除</el-button>
          <el-button @click="UpdateStatus(supplierForm.sup_status)" class="white-black-btn" size="small">
            {{ supplierForm.sup_status === 0 ? '停用' : '启用' }}
          </el-button>
        </div>
      </div>
      
      <div class="divider"></div>
      
      <!-- 使用网格布局的基础资料部分 -->
      <div class="basic-info-grid">
        
        <div class="info-item">
          <div class="info-label">所属行业</div>
          <div class="info-value">{{supplierForm.sup_industry}}</div>
        </div>
        
        <div class="info-item">
          <div class="info-label">供应商分类</div>
          <div class="info-value">{{supplierForm.sup_type}}</div>
        </div>
        
        <div class="info-item">
          <div class="info-label">联系人</div>
          <div class="info-value">{{ supplierForm.sup_linkman }}</div>
        </div>
        
        <div class="info-item">
          <div class="info-label">状态</div>
          <div class="info-value">{{ supplierForm.sup_status === 1 ? '停用' : '启用' }}</div>
        </div>
        
        <div class="info-item">
          <div class="info-label">联系电话</div>
          <div class="info-value">{{ supplierForm.sup_linkphone }}</div>
        </div>
        
        <div class="info-item">
          <div class="info-label">电子邮箱</div>
          <div class="info-value">{{ supplierForm.sup_email }}</div>
        </div>
        
        <div class="info-item">
          <div class="info-label">进货部门</div>
          <div class="info-value">{{ supplierForm.sup_depName }}</div>
        </div>
        
        <div class="info-item">
          <div class="info-label">进货负责人</div>
          <div class="info-value">{{ supplierForm.sup_userName }}</div>
        </div>
        
        <!-- 地址跨2列 -->
        <div class="info-item full-row">
          <div class="info-label">供应商地址</div>
          <div class="info-value">{{ supplierForm.sup_address }}</div>
        </div>
        
        <!-- 备注跨2列 -->
        <div class="info-item full-row">
          <div class="info-label">备注</div>
          <div class="info-value">{{ supplierForm.remark }}</div>
        </div>
        
        <div class="info-item">
          <div class="info-label">创建人</div>
          <div class="info-value">{{ supplierForm.create_name }}</div>
        </div>
        
        <div class="info-item">
          <div class="info-label">创建时间</div>
          <div class="info-value">{{ supplierForm.create_time }}</div>
        </div>
        
        <div class="info-item">
          <div class="info-label">更新人</div>
          <div class="info-value">{{ supplierForm.update_name }}</div>
        </div>
        
        <div class="info-item">
          <div class="info-label">更新时间</div>
          <div class="info-value">{{ supplierForm.update_time }}</div>
        </div>
      </div>
    </div>
    
    <!-- 下方容器：其他信息 -->
    <div class="other-info-container">
      <div class="section-header">
        <div class="section-tabs">
          <div 
            v-for="(tab, index) in tabs" 
            :key="index"
            :class="['tab-item', { active: activeTab === tab }]"
            @click="activeTab = tab"
          >
            {{ tab }}
          </div>
        </div>
      </div>
      
      <div class="divider"></div>
      
      <div v-if="activeTab === '其他信息'" class="tab-content">
        <!-- 使用网格布局的基础资料部分 -->
        <div class="section-header">
          <div class="section-title">财务信息</div>
        </div>
        <div class="Additional-Information">
          <div class="info-item">
            <div class="info-label">账户名称</div>
            <div class="info-value">{{supplierForm.sup_accountName}}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">纳税人识别号</div>
            <div class="info-value">{{supplierForm.sup_taxpayerNum}}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">银行账户</div>
            <div class="info-value">{{ supplierForm.sup_bankAccount }}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">开户银行</div>
            <div class="info-value">{{ supplierForm.sup_openBank }}</div>
          </div>
          
          <div class="info-item">
            <div class="info-label">开户行地址</div>
            <div class="info-value">{{ supplierForm.sup_openBankAddress }}</div>
          </div>
        </div>
        <div class="section-header">
          <div class="section-title">附件</div>
        </div>
        <el-table 
          :data="filelist" 
          @row-click="handleRowClick"
          style="width: 100%"
          >
          <el-table-column label="文件名">
            <template #default="scope">
              <el-link type="primary" :underline="false">
                <el-icon><Document /></el-icon>
                <span style="margin-left: 8px">{{ scope.row.title }}</span>
              </el-link>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-if="activeTab === '进货记录'" class="tab-content">
      <div style="text-align: left;">
          <el-button @click="exportData()">导出</el-button>
      </div>
        <!--表格-->
        <el-table :data="purdata"  stripe style="margin-top: 10px;" @selection-change="SelectChange">
            <el-table-column fixed  type="selection"></el-table-column>
            <el-table-column fixed prop="pur_id" label="序号"></el-table-column>

            <el-table-column fixed  label="进货单号" width="200px">
                <template #default="scope">
                    <span style="color: green;cursor: pointer;" @click="ShowInfo(scope.row)">{{ scope.row.pur_code }}</span>
                </template>
            </el-table-column>
            <el-table-column fixed prop="pur_status" label="单据状态"></el-table-column>
            <el-table-column fixed prop="pur_date" label="进货日期" width="200px"></el-table-column>
            <el-table-column prop="sup_name" label="供应商" width="200px"></el-table-column>
            <el-table-column prop="sup_linkman" label="联系人"></el-table-column>
            <el-table-column prop="sup_linkphone" label="联系方式" width="200px"></el-table-column>
            <el-table-column prop="pur_depName" label="进货部门" width="120px"></el-table-column>
            <el-table-column prop="pur_userName" label="进货人"></el-table-column>
            <el-table-column prop="pur_num" label="货品数量"></el-table-column>
            <el-table-column prop="pur_total" label="货品金额"></el-table-column>
            <el-table-column prop="proc_list"  label="进货货品" width="300px"></el-table-column>
            <el-table-column prop="create_name" label="制单人"></el-table-column>
            <el-table-column prop="create_time" label="制单时间" width="200px"></el-table-column>
            <el-table-column prop="approver_name" label="审核人"></el-table-column>
            <el-table-column prop="approver_time" label="审核时间" width="200px"></el-table-column>
          </el-table>
      </div>
      <div v-if="activeTab === '出库记录'" class="tab-content">
          <!-- 导出按钮 -->
          <div style="text-align: left; margin-bottom: 10px;">
              <el-button @click="outExport">导出</el-button>
          </div>

          <!-- 表格展示 -->
          <el-table :data="outstockdata" stripe style="margin-top: 10px;" @selection-change="outSelectChange">
              <!-- 固定列和数据展示列 -->
              <el-table-column fixed type="selection"></el-table-column>
              <el-table-column fixed type="index" label="序号" width="80"></el-table-column>
              <el-table-column fixed label="出库单号" width="200px">
                  <template #default="scope">
                      <span style="color: green; cursor: pointer;" @click="ShowOutstockInfo(scope.row)">
                          {{ scope.row.out_code }}
                      </span>
                  </template>
              </el-table-column>
              <el-table-column fixed prop="out_type" label="出库类型"></el-table-column>
              <el-table-column fixed prop="out_status" label="状态"></el-table-column>
              <el-table-column fixed prop="out_date" label="出库日期" width="180px"></el-table-column>
              <el-table-column prop="wh_name" label="仓库名称" width="150px"></el-table-column>
              <el-table-column prop="out_order" label="关联单号" width="200px"></el-table-column>
              <el-table-column label="出库货品" width="300px">
                  <template #default="scope">
                      <el-tooltip
                          effect="dark"
                          :content="scope.row.proc_list_full"
                          placement="top"
                          :disabled="!scope.row.proc_list_full || scope.row.proc_list_full.split('、').length <= 3"
                      >
                          <span>{{ scope.row.proc_list }}</span>
                      </el-tooltip>
                  </template>
              </el-table-column>
              <el-table-column prop="out_user" label="经办人"></el-table-column>
              <el-table-column prop="out_num" label="出库数量"></el-table-column>
              <el-table-column prop="out_total" label="出库金额" width="120px"></el-table-column>
              <el-table-column prop="create_name" label="制单人"></el-table-column>
              <el-table-column prop="create_time" label="制单时间" width="200px"></el-table-column>
              <el-table-column prop="approver_name" label="审核人"></el-table-column>
              <el-table-column prop="approver_time" label="审核时间" width="200px"></el-table-column>
          </el-table>
      </div>
      <div v-if="activeTab === '入库记录'" class="tab-content">
            <!--仅保留导出按钮和表格展示-->
            <div style="text-align: left; margin-bottom: 10px;">
                <el-button @click="inExport">导出</el-button>
            </div>

            <!--表格展示部分保留只读展示-->
            <el-table :data="instockdata" stripe style="margin-top: 10px;" @selection-change="inSelectChange">
              <!--固定列和数据展示列保留-->
              <el-table-column fixed type="selection"></el-table-column>
              <el-table-column fixed type="index" label="序号" width="100"></el-table-column>
              <el-table-column fixed label="入库单号" width="200px">
                  <template #default="scope">
                      <span style="color: green; cursor: pointer;" @click="ShowInstockInfo(scope.row)">
                          {{ scope.row.in_code }}
                      </span>
                  </template>
              </el-table-column>
              <el-table-column fixed prop="in_type" label="入库类型"></el-table-column>
              <el-table-column fixed prop="in_status" label="状态"></el-table-column>
              <el-table-column fixed prop="in_date" label="入库日期" width="200px"></el-table-column>
              <el-table-column prop="wh_name" label="仓库名称" width="200px"></el-table-column>
              <el-table-column prop="in_order" label="关联单号" width="200px"></el-table-column>
              <el-table-column label="入库货品" width="300px">
                  <template #default="scope">
                      <el-tooltip
                          effect="dark"
                          :content="scope.row.proc_list_full"
                          placement="top"
                          :disabled="!scope.row.proc_list_full || scope.row.proc_list_full.split('、').length <= 3"
                      >
                          <span>{{ scope.row.proc_list }}</span>
                      </el-tooltip>
                  </template>
              </el-table-column>
              <el-table-column prop="in_user" label="经办人"></el-table-column>
              <el-table-column prop="in_num" label="入库数量"></el-table-column>
              <el-table-column prop="in_total" label="入库金额" width="120px"></el-table-column>
              <el-table-column prop="create_name" label="制单人"></el-table-column>
              <el-table-column prop="create_time" label="制单时间" width="200px"></el-table-column>
              <el-table-column prop="approver_name" label="审核人"></el-table-column>
              <el-table-column prop="approver_time" label="审核时间" width="200px"></el-table-column>
          </el-table>
      </div>
    </div>
    <!-- 底部操作栏 -->
    <div class="action-bar">
      <el-button @click="Close">关闭</el-button>
    </div>
  </div>
</template>

<script>
import { useRouter, useRoute } from 'vue-router'
import {ref,reactive,onMounted} from 'vue';
import http from '../auth/index';
import { ElMessage,ElMessageBox  } from 'element-plus'; //提示信息
import { Document } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx';
export default {
  setup(){
    const router = useRouter();
    const route = useRoute(); // 获取路由实例
    const id = ref(route.query ? route.query.id || null : null);

    // 选项卡数据
    const tabs = ['其他信息', '进货记录', '出库记录', '入库记录'];
    const activeTab = ref('其他信息');

    // 过滤条件
    const filter = reactive({
      operationType: '',
      operator: '',
      operationTime: ''
    });

    // 操作记录数据
    const filelist = ref([])//附件存储数组

    // 行点击事件
    function handleRowClick(row) {
      if (!row.file_name) {
        ElMessage.error('文件URL不存在，请重新上传');
        return;
      }

      const ext = row.title.split('.').pop().toLowerCase();

      switch (ext) {
        case 'jpg':
        case 'jpeg':
        case 'png':
        case 'gif':
        case 'bmp':
        case 'pdf':
        case 'doc':
        case 'docx':
        case 'xls':
        case 'xlsx':
        case 'ppt':
        case 'txt':
        case 'pptx':
          window.open(row.file_name, '_blank');
          break;
        default:
          const link = document.createElement('a');
          link.href = row.file_name;
          link.download = row.title;
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
      }
    }

    // 获取附件数据的方法
    function GetPublicFile() {
      const code = route.query ? route.query.code || null : null
      http.get("/PublicFile/GetPublicFileBy", {
        params: {
          type: "供应商",
          code: code,
        }
      }).then(res => {
        // 根据映射类调整数据结构
        console.log("附件:", res.data); // 调试用
        filelist.value = res.data;
      }).catch(err => {
        console.log(err)
        ElMessage.error('附件加载失败')
      })
    }

    const pageSize = ref(10);
    const totalItems = ref(100);

    const supplierForm = reactive({
      sup_code: "",
      sup_name: "",
      sup_industry: "",
      sup_type: "",
      sup_linkman: "",
      sup_linkphone: "",
      sup_email: "",
      sup_depId: null,
      sup_userId: null,
      sup_status: 0,
      sup_address: "",
      remark: "",
      sup_accountName: "",
      sup_taxpayerNum: "",
      sup_bankAccount: "",
      sup_openBank: "",
      sup_openBankAddress: "",
      create_name: "",
      create_time: "",
      update_name: "",
      update_time: "",
      sup_depName:"",
      sup_userName:""
    });

    // 查询Id查供应商数据
    function GetIdSupplier() {
      http.get("/Supplier/GetIdSupplier", {
          params: {
              id: id.value
          }
      }).then(res => {
          const apiData = res.data;
          console.log("ID供应商:", apiData); // 调试用
          Object.assign(supplierForm, processSupplierData(apiData));
      }).catch(err => {
          console.log(err);
          ElMessage.error('数据加载失败');
      });
    }

    // 封装数据处理逻辑
    function processSupplierData(apiData) {
      return {
        sup_code: apiData.sup_code || "",
        sup_name: apiData.sup_name || "",
        sup_industry: apiData.sup_industry || "",
        sup_type: apiData.sup_type || "",
        sup_linkman: apiData.sup_linkman || "",
        sup_linkphone: apiData.sup_linkphone || "",
        sup_email: apiData.sup_email || "",
        sup_depId: apiData.sup_depId || null,
        sup_userId: apiData.sup_userId || null,
        sup_status: apiData.sup_status || 0,
        sup_address: apiData.sup_address || "",
        remark: apiData.remark || "",
        sup_accountName: apiData.sup_accountName || "",
        sup_taxpayerNum: apiData.sup_taxpayerNum || "",
        sup_bankAccount: apiData.sup_bankAccount || "",
        sup_openBank: apiData.sup_openBank || "",
        sup_openBankAddress: apiData.sup_openBankAddress || "",
        create_name: apiData.create_name || "" ,
        create_time: apiData.create_time || "",
        update_name: apiData.update_name || "",
        update_time: apiData.update_time || "",
        sup_depName:apiData.sup_depName||"",
        sup_userName:apiData.sup_userName||""
      };
    }

    // 删除供应商方法
    function deleteSupplier() {
      ElMessageBox.confirm('确定要删除该供应商吗？', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
      }).then(async () => {
          try {
          // 调用后端逻辑删除接口（PUT 方法）
          const res = await http.put('/Supplier/DeleteSupplier?id='+id.value);
          if (res.status === 200) {
              ElMessage.success('删除成功');
              router.push('supplier');
          }
          } catch (err) {
          ElMessage.error('删除失败');
          console.error(err);
          }
      }).catch(() => {
          ElMessage.success('删除已取消');
      });
    }

    //启用/停用
    async function UpdateStatus(status) {
      ElMessageBox.confirm(supplierForm.sup_status === 0 ? '确定要停用该供应商吗？' : '确定要启用该供应商吗？','提示',{
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
      }).then(async () => {
          try {
          const res = await http.put('/Supplier/UpdateStatus?sup_id='+id.value+'&sup_status='+status);
          if (res.status === 200) {
              ElMessage.success(supplierForm.sup_status === 0 ? '成功停用' : '成功启用');
              GetIdSupplier()
          }
          } catch (err) {
          ElMessage.error(supplierForm.sup_status === 0 ? '停用失败' : '启用失败');
          console.error(err);
          }
      }).catch(() => {
          ElMessage.success(supplierForm.sup_status === 0 ? '停用已取消' : '启用已取消');
      });
    }

    function JumptoEdit() {
      router.push({ path: 'suppliernew', query: { id: id.value ,Detail:true} });
    }

            //日期转换格式
            function formatDateTime(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }

        // 货品列表格式化函数
        function formatProductList(products) {
            if (!products) return "";
            const productArray = Array.isArray(products) 
                ? products 
                : products.split('、').filter(Boolean);
            
            if (productArray.length <= 3) {
                return productArray.join('、');
            } else {
                const firstThree = productArray.slice(0, 3).join('、');
                return `${firstThree}等${productArray.length}项....`;
            }
        }

        //查询所有单据状态
        const status=ref([]);
        function GetStatus(){
            return http.get("/DictData/GetAllDictDataBytype?typeid=6")
            .then(res=>{
                status.value=res.data;
            }).catch(err=>{
                console.log(err);
            })
        }

        function getStatusLabel(value, dict) {
          const found = dict.find(item => item.dict_value == value);
          return found ? found.dict_label : "未知状态";
        }

        const purform=reactive({
            code:"",
            ordstatus:"",
            sup:"",
            date:[null,null]
        })

        //表格数据
        const purdata = ref([]);
        //当前页
        const currentPage = ref(1);
        
        //#region 查看详情信息
        function ShowInfo(row){
          router.push({
            name:"purchaseinfo",
            params:{
              purid:row.pur_id,
              purcode:row.pur_code
            }
          })
        }

        
        //查询数据
        function All(){
            http.get("/Purchase_h/GetPurchase_h", {
                params: {
                    code: "",
                    status: null,
                    sup:id.value,
                    starttime:"",
                    endtime:"",
                    CurrentPage: currentPage.value
                }
            }).then(res => {
                if (res.data.list.length == 0 && activeTab.value === '进货记录') {
                    ElMessage({
                        message: '没有相关数据.',
                        type: 'warning',
                    })
                }
                //数据转换
                const Data = res.data.list.map(item => ({
                    ...item,
                    pur_date: formatDateTime(new Date(item.pur_date)),
                    create_time: formatDateTime(new Date(item.create_time)),
                    approver_time: item.approver_time ? formatDateTime(new Date(item.approver_time)) : "",
                    pur_total: item.pur_total ? Number(item.pur_total).toFixed(2) : "0.00",
                    proc_list: formatProductList(item.proc_list),
                    pur_status: getStatusLabel(item.pur_status, status.value),
                }));
                purdata.value = Data;
                console.log("查询数据:", purdata.value);
            }).catch(err => {
                console.log(err)
            })
        }

        //改变页数
        function handlePageChange(page) {
            currentPage.value = page
            All();
        }

        //导出：开始
        // 定义选中的表格数据
        const selectdata = ref([]);

        // 处理表格选择变化
        function SelectChange(selectedRows) {
          selectdata.value = selectedRows;
        }

        function exportData() {
            if (selectdata.value.length === 0) {
                ElMessage.warning('请选择要导出的数据');
                return;
            }
    
            // 创建工作簿
            const wb = XLSX.utils.book_new();
            const excelData = selectdata.value.map((row) => ({
                '序号': row.pur_id,
                '进货单号': row.pur_code,
                '单据状态': row.pur_status,
                '进货日期': row.pur_date,
                '供应商': row.sup_name,
                '联系人': row.sup_linkman,
                '联系方式': row.sup_linkphone,
                '进货部门': row.pur_depName,
                '进货人': row.pur_userName,
                '货品数量': row.pur_num,
                '货品金额': row.pur_total,
                '进货货品': row.proc_list,
                '制单人': row.create_name,
                '制单时间': row.create_time,
                '审核人': row.approver_name,
                '审核时间': row.approver_time
            }));
            // 创建工作表
            const ws = XLSX.utils.json_to_sheet (excelData);
            // 添加到工作簿
            XLSX.utils.book_append_sheet(wb, ws, "供应商数据");
            // 导出并下载
            XLSX.writeFile(wb, `供应商${supplierForm.sup_name}的进货记录${new Date().toLocaleDateString()}.xlsx`);
        }
        //导出：结束

        //#region 入库记录
        // 数据格式化工具函数保留
        function formatGoodsList(goods) {
            if (!goods) return "";
            const goodsArray = Array.isArray(goods) ? goods : goods.split('、').filter(Boolean);
            if (goodsArray.length <= 3) {
                return goodsArray.join('、');
            } else {
                const firstThree = goodsArray.slice(0, 3).join('、');
                return `${firstThree}等${goodsArray.length}项....`;
            }
        }

        // 表格数据相关
        const instockdata = ref([]);
        const incurrentPage = ref(1);
        const inselectdata = ref([]);

        // 初始化数据加载（无条件加载全部数据）
        function InLoadData() {
          http.get("/Instock_h/GetInstock_hSup", {
              params: { 
                CurrentPage:incurrentPage.value,
                sup_id:id.value
              }
          }).then(res => {
              // 添加空数组防护
              const listData = res.data?.list || [];
              
              const Data = listData.map(item => ({
                  ...item,
                  in_date: formatDateTime(new Date(item.in_date)),
                  create_time: formatDateTime(new Date(item.create_time)),
                  approver_time: item.approver_time ? formatDateTime(new Date(item.approver_time)) : "",
                  in_total: item.in_total ? Number(item.in_total).toFixed(2) : "0.00",
                  proc_list_full: item.proc_list,
                  proc_list: formatGoodsList(item.proc_list)
              }));
              
              instockdata.value = Data;
          }).catch(error => {
              console.error("加载入库记录失败:", error);
              ElMessage.error("加载入库记录失败");
              instockdata.value = [];
          });
        }

        // 分页处理
        function inhandlePageChange(page) {
            incurrentPage.value = page;
            InLoadData();
        }

        // 多选数据收集
        function inSelectChange(val) {
            inselectdata.value = val;
        }

        // 导出功能
        function inExport() {
            if (inselectdata.value.length == 0) {
                ElMessage({ message: '请选择要导出的数据.', type: 'warning' });
                return;
            }
            const wb = XLSX.utils.book_new();
            const excelData = inselectdata.value.map((row) => ({
                "入库单号": row.in_code,
                "入库类型": row.in_type,
                "状态": row.in_status,
                "入库日期": row.in_date,
                "仓库名称": row.wh_name,
                "关联单号": row.in_order,
                "入库货品": row.proc_list,
                "经办人": row.in_user,
                "入库数量": row.in_num,
                "入库金额": row.in_total,
                "制单人": row.create_name,
                "制单时间": row.create_time,
                "审核人": row.approver_name,
                "审核时间": row.approver_time
            }));
            const ws = XLSX.utils.json_to_sheet(excelData);
            XLSX.utils.book_append_sheet(wb, ws, "入库单");
            XLSX.writeFile(wb, `入库单${new Date().toLocaleDateString()}.xlsx`);
        }

        function ShowInstockInfo(row) {
          // 假设入库详情页的路由名称是 'instockinfo'，请根据实际路由配置调整
          console.log("入库跳转:", row); // 调试用
          router.push({
              name: "instockinfo",
              params: {
                  instockid: row.in_id,
                  instockcode: row.in_code
              }
          });
        }
      //#endregion

      //#region 出库记录
      function formatGoodsList(goods) {
          if (!goods) return "";
          const goodsArray = Array.isArray(goods) ? goods : goods.split('、').filter(Boolean);
          if (goodsArray.length <= 3) {
              return goodsArray.join('、');
          } else {
              const firstThree = goodsArray.slice(0, 3).join('、');
              return `${firstThree}等${goodsArray.length}项....`;
          }
      }

      // 表格数据相关
      const outstockdata = ref([]);
      const outcurrentPage = ref(1);
      const outselectdata = ref([]);

      // 初始化数据加载
      function OutLoadData() {
        http.get("/Outstock_h/GetOutstock_hSup", {
            params: { 
              CurrentPage:outcurrentPage.value,
              sup_id:id.value
            }
        }).then(res => {
            // 添加空数组防护
            const listData = res.data?.list || [];
            
            const Data = listData.map(item => ({
                ...item,
                out_date: formatDateTime(new Date(item.out_date)),
                create_time: formatDateTime(new Date(item.create_time)),
                approver_time: item.approver_time ? formatDateTime(new Date(item.approver_time)) : "",
                out_total: item.out_total ? Number(item.out_total).toFixed(2) : "0.00",
                proc_list_full: item.proc_list,
                proc_list: formatGoodsList(item.proc_list)
            }));
            
            outstockdata.value = Data;
        }).catch(error => {
            console.error("加载出库记录失败:", error);
            ElMessage.error("加载出库记录失败");
            outstockdata.value = [];
        });
      }

      // 分页处理
      function outhandlePageChange(page) {
          outcurrentPage.value = page;
          OutLoadData();
      }

      // 多选数据收集
      function outSelectChange(val) {
          outselectdata.value = val;
      }

      // 导出功能
      function outExport() {
          if (outselectdata.value.length == 0) {
              ElMessage({ message: '请选择要导出的数据.', type: 'warning' });
              return;
          }
          const wb = XLSX.utils.book_new();
          const excelData = outselectdata.value.map((row) => ({
              "出库单号": row.out_code,
              "出库类型": row.out_type,
              "状态": row.out_status,
              "出库日期": row.out_date,
              "仓库名称": row.wh_name,
              "关联单号": row.out_order,
              "出库货品": row.proc_list,
              "经办人": row.out_user,
              "出库数量": row.out_num,
              "出库金额": row.out_total,
              "制单人": row.create_name,
              "制单时间": row.create_time,
              "审核人": row.approver_name,
              "审核时间": row.approver_time
          }));
          const ws = XLSX.utils.json_to_sheet(excelData);
          XLSX.utils.book_append_sheet(wb, ws, "出库单");
          XLSX.writeFile(wb, `出库单${new Date().toLocaleDateString()}.xlsx`);
      }

      function ShowOutstockInfo(row) {
          // 假设出库详情页的路由名称是 'outstockinfo'，请根据实际路由配置调整
          router.push({
              name: "outstockinfo",
              params: {
                  outstockid: row.out_id,
                  outstockcode: row.out_code
              }
          });
      }
      //#endregion

    //挂载
    onMounted(() => {
      InLoadData()
      OutLoadData()
      GetIdSupplier()
      GetPublicFile()
      All()
      GetStatus()
    });

    //关闭
    function Close(){
      router.back();
    }

    return{
      //#region 出库记录
      ShowOutstockInfo,
      outstockdata,
      outhandlePageChange,
      outSelectChange,
      outExport,
      //#endregion
      //#region 入库记录
      ShowInstockInfo,
      incurrentPage,
      instockdata,
      inhandlePageChange,
      inselectdata,
      inSelectChange,
      inExport,
      //#endregion
      selectdata,
      SelectChange,
      UpdateStatus,
      Close,
      ShowInfo,
      exportData,
      handlePageChange,
      All,
      status,
      purform,
      purdata,
      handleRowClick,
      tabs,
      activeTab,
      filter,
      currentPage,
      pageSize,
      totalItems,
      supplierForm,
      GetIdSupplier,
      deleteSupplier,
      JumptoEdit,
      filelist
    }
  }
}
</script>

<style scoped>
/* 底部操作栏自适应 */
.action-bar {
  position: fixed;
  bottom: 0;
  right: 0.5%; /* 与表单右侧对齐 */
  left: 210px; /* 与菜单栏宽度一致 */
  background: white;
  border-top: 1px solid #e6e6e6;
  padding: 15px;
  text-align: right;
}

.supplier-detail {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding: 20px;
  width: 70%;
}

/* 通用样式 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 5px 0 15px;
}

/* 基础资料容器 */
.basic-info-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #1a1a1a;
}

.section-actions {
  display: flex;
  gap: 10px;
}

/* 灵活的基础资料网格布局 */
.basic-info-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr); /* 固定3列 */
  gap: 24px;
}

@media (max-width: 1200px) {
  .basic-info-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .basic-info-grid {
    grid-template-columns: 1fr;
  }
}

.info-item {
  display: flex;
  min-height: 36px;
}

.info-label {
  width: 100px;
  color: #1a1a1a;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.info-value {
  flex: 1;
  font-size: 14px;
  color: #a0a0a0;
  font-weight: 500;
  display: flex;
  align-items: center;
  padding-left: 10px;
}

/* 跨行显示的元素 */
.full-row {
  grid-column: 1 / -1;
  display: flex;
}

.full-row .info-label {
  width: 100px;
}

.full-row .info-value {
  flex: 1;
}

/* 其他信息容器 */
.other-info-container {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.section-tabs {
  display: flex;
  border-bottom: 1px solid #ebeef5;
  width: 100%;
}

.tab-item {
  padding: 8px 20px;
  cursor: pointer;
  font-size: 14px;
  position: relative;
  color: #606266;
}

.tab-item.active {
  color: #45b984;
  font-weight: 500;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 0;
  width: 100%;
  height: 2px;
  background: #45b984;
}

/* 灵活的基础资料网格布局 */
.Additional-Information {
  display: grid;
  grid-template-columns: repeat(2, 1fr); /* 固定3列 */
  gap: 24px;
}

@media (max-width: 1200px) {
  .Additional-Information {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .Additional-Information {
    grid-template-columns: 1fr;
  }
}

/* 操作记录部分 */
.filter-section {
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  gap: 15px;
  margin-bottom: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 10px;
}

.filter-label {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  margin-top: 20px;
}

.total-items {
  color: #606266;
  font-size: 14px;
}

.page-size-select {
  display: flex;
  align-items: center;
  color: #606266;
  font-size: 14px;
  gap: 8px;
}
</style>